import { ref, computed } from 'vue'
import { defineStore } from 'pinia'
// import api from '@/api'

export const useUserStore = defineStore('user', () => {
  // 安全地解析localStorage中的数据
  const getStoredUsers = () => {
    try {
      const stored = localStorage.getItem("users")
      return stored ? JSON.parse(stored) : { username: '', password: '' }
    } catch (error) {
      console.warn('Failed to parse users from localStorage:', error)
      return { username: '', password: '' }
    }
  }

  const getStoredUserInfo = () => {
    try {
      const stored = localStorage.getItem("userInfo")
      return stored ? JSON.parse(stored) : null
    } catch (error) {
      console.warn('Failed to parse userInfo from localStorage:', error)
      return null
    }
  }

  const user = ref(getStoredUsers())
  let userInfo = ref(getStoredUserInfo())
  const token = ref(localStorage.getItem('token') || '')
  const isAuthenticated = computed(() => !!token.value)
  
  // 添加头像状态管理
  const userAvatar = ref('')

  let remember=(value)=>{
    user.value=value
  }

  let setUserInfo=(value)=>{
    userInfo.value=value
  }

  // 设置头像URL
  const setUserAvatar = (avatarUrl) => {
    userAvatar.value = avatarUrl
  }

  // 更新头像URL
  const updateUserAvatar = (avatarUrl) => {
    userAvatar.value = avatarUrl
  }

  // 登出
  const logout = () => {
    token.value = ''
    user.value = null
    userAvatar.value = ''
    localStorage.removeItem('token')
  }

  // 获取用户信息
  const getUserInfo = async () => {
    try {
      const response = await api.get('/auth/me')
      user.value = response
      return response
    } catch (error) {
      throw error
    }
  }

  // 检查认证状态
  const checkAuth = async () => {
    if (token.value) {
      try {
        await getUserInfo()
        return true
      } catch (error) {
        logout()
        return false
      }
    }
    return false
  }

  return {
    remember,
    user,
    setUserInfo,
    userAvatar,
    setUserAvatar,
    updateUserAvatar
  }
  
}) 